package com.tmc.service.baseinfo;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.dao.impl.DeptDaoImpl;
import com.tmc.dao.impl.EthAgentDaoImpl;
import com.tmc.dao.impl.UserDaoImpl;
import com.tmc.entity.common.EthAgent;
import com.tmc.entity.common.EthDept;
import com.tmc.entity.common.EthUser;
import com.tmc.util.ObjectUtil;

@Service
@Transactional
public class EthUserServiceImpl {
	@Autowired
	private UserDaoImpl userDao;
	
	@Autowired
	private DeptDaoImpl deptDao;
	
	@Autowired
	private EthAgentDaoImpl agentDao;
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	public Pagination<EthUser> findByCond(ContextInfo contextInfo, EthUser cond, Integer pageIndex, Integer pageSize) {
		Pagination<EthUser> result = userDao.findByCond(contextInfo, cond, pageIndex, pageSize);
		this.setExtInfo(result.getItems());
		return result;
	}
	
	public EthUser getUserById(ContextInfo context, Long userId) {
		if (userId == null) {
			return null;
		}
		EthUser result = userDao.getById(userId);
		EthAgent agent = agentDao.getById(result.getAgentId());
		result.setAgent(agent);
		this.setExtInfo(result);
		return result;
	}
	
	private void setExtInfo(List<EthUser> result) {
		if (result == null || result.isEmpty()) {
			return;
		}
		for (EthUser user : result) {
			this.setExtInfo(user);
		}
	}
	
	private void setExtInfo(EthUser result) {
		if (result == null) {
			return;
		}
		EthDept dept = deptDao.getById(result.getDeptId());
		if(dept !=null ){
			result.setDeptName(dept.getDeptName());;
		}
		
		String userCode = result.getUserCode();
		if (userCode.indexOf("_") > -1){
			result.setUserCode4Show(userCode.substring(userCode.indexOf("_") + 1));
		}
		if (result.getVipLevel() > 1) {
			result.setManagerFlag("是");
		} else {
			result.setManagerFlag("否");
		}
		result.setRoleName(this.getRoleName(result.getVipLevel()));
	}
	
	private String getRoleName(Integer vipLevel) {
		if (vipLevel == 1){
			return "普通员工";
		}
		if (vipLevel == 2){
			return "部门管理员";
		}
		if (vipLevel == 3){
			return "公司管理员";
		}
		return "";
	}

	
	public CommonResult save(ContextInfo context,EthUser vendor){
		CommonResult check= this.check(vendor);
		if(!check.isSuccess()){
			return check;
		}
		
		// 部门
		if (vendor.getDeptId() == null && ObjectUtil.hasText(vendor.getDeptName())) {
			EthDept dept = deptDao.getByName(context, vendor.getDeptName());
			if(dept == null){
				return CommonResult.makeFail(vendor.getDeptName() + "部门不存在！");
			}
			vendor.setDeptId(dept.getDeptId());
		}
		//保存
		if(vendor.getUserId() == null){
			if (vendor.getVipLevel() == null){
				vendor.setVipLevel(1);
			}
			vendor.setUserCode("THHK_" + vendor.getUserCode4Show());
			ObjectUtil.setBaseInfo(vendor, context);
			userDao.insert(vendor);
		} else {
			try {
				EthUser dbUser = userDao.getById(vendor.getUserId());
				vendor.setUserCode("THHK_" + vendor.getUserCode4Show());
				if(dbUser != null){
					ObjectUtil.copyProperties(vendor, dbUser,
							new String[] { "createdBy", "creationDate", "userId", "enabledFlag" });
				}
				ObjectUtil.updateBaseInfo(dbUser, context);
				userDao.update(dbUser);
			} catch (Exception e) {
				logger.error("拷贝对象错误！", e);
				return CommonResult.makeFail("拷贝对象错误！");
			}
		}
		return CommonResult.makeSuccess();
	}
	
	public CommonResult updatePhone(ContextInfo context, EthUser user) {
		EthUser dbuser = userDao.getById(user.getUserId());
		if(dbuser == null){
			return CommonResult.makeFail("用户未登入！");
		}
		if(ObjectUtil.noText(user.getPhone())){
			return CommonResult.makeFail("手机号不能为空！");
		}
		dbuser.setPhone(user.getPhone());
		ObjectUtil.updateBaseInfo(dbuser, context);
		userDao.update(dbuser);
		return CommonResult.makeSuccess();
	}
	
	public CommonResult updatePassword(ContextInfo context,EthUser user){
		EthUser dbuser = userDao.getById(user.getUserId());
		if(dbuser == null){
			return CommonResult.makeFail("用户未登入！");
		}
		if(!dbuser.getPassword().equals(user.getPassword())){
			return CommonResult.makeFail("输入密码不正确");
		}
		if(!user.getNewPassword().equals(user.getConfirmPassword())){
			return CommonResult.makeFail("请保持两次输入一致！");
		}
		dbuser.setPassword(user.getNewPassword());
		ObjectUtil.updateBaseInfo(dbuser, context);
		userDao.update(dbuser);
		return CommonResult.makeSuccess();
	}

	public List<EthUser> searchOperator(String query) {
		List<EthUser> users = new ArrayList<EthUser>();
		List<EthUser> dbList = null;
		if (ObjectUtil.noText(query)) {
			Pagination<EthUser> result = userDao.findByCond(new ContextInfo(), new EthUser(), 1, 10);
			dbList = result.getItems();
		} else {
			dbList = userDao.findListByName(new ContextInfo(), query);
		}
		for (EthUser user : dbList) {
			if (user.getUserCode().indexOf(query) > -1 || user.getUserName().indexOf(query) > -1) {
				users.add(user);
				if (users.size() == 5) {
					return users;
				}
			}
		}
		return users;
	}
	
	private CommonResult check(EthUser vendor) {
		if(ObjectUtil.noText(vendor.getUserCode4Show())){
			CommonResult.makeFail("编码不能为空！");
		}
		if (!ObjectUtil.hasText(vendor.getUserName())) {
			return CommonResult.makeFail("名字不能为空！");
		}
		String userCode="THHK_"+vendor.getUserCode4Show();
		EthUser dbUser = userDao.getByUserCode(userCode);
		if (dbUser != null && !dbUser.getUserId().equals(vendor.getUserId())) {
			return CommonResult.makeFail("已存在用户名为" + userCode + "的用户！");
		}
		if (vendor.getVipLevel() > 3){
			return CommonResult.makeFail("员工角色错误！");
		}
		return CommonResult.makeSuccess();
	}

	public CommonResult delete(ContextInfo context, Long userId) {
		EthUser dbUser = userDao.getById(userId);
		if (dbUser != null) {
			ObjectUtil.updateBaseInfo(dbUser, context);
			dbUser.setEnabledFlag("N");
			userDao.update(dbUser);
		} else {
			return CommonResult.makeFail("数据不存在！");
		}
		return CommonResult.makeSuccess("删除成功！");
	}


	
}
